package com.bems.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;

import com.bems.jdbc.common.QueryHelper;
import com.bems.pojo.Bill;
import com.bems.pojo.Code;
import com.bems.pojo.List;
import com.bems.pojo.POJO;
import com.bems.pojo.Type;
import com.bems.pojo.User;
import com.bems.pojo.Ware;


/**
 * 
 * @author 陈磊
 *
 */
public class ListDao extends BaseDao 
{
	
	
	/**
	 *  出库，报废
	 * @param list
	 * @return
	 */
	public Long out(List list) 
	{
		list.setId(0);
		if (list.getNumber()==null||list.getWarehouse_id()<0||list.getType_id()<0) {
			return null;
		}
		
		if(list.getStocknumber()!=null)
		{
		
			//修改库存
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("stocknumber", list.getStocknumber());
			map.put("type_id",list.getType_id());
			Ware ware = new Ware().get(map );
			if(ware!=null)
			{
				if(ware.getQuantity()-list.getQuantity()<0)
					return Long.parseLong("-1");
				if(ware.getQuantity()-list.getQuantity()==0)
				{
					//删除
					ware.delete();
				}else {
					map.remove("stocknumber");
					map.remove("type_id");
					map.put("quantity", ware.getQuantity()-list.getQuantity());
					ware.update(map,ware.getId());
				}
				
			}else {
				return Long.parseLong("-1");
				
			}
		}
		else {
			return null;
		}
		
		long id = list.save();
	
		
		return id;

	}
	
	
	/**
	 * 出库，报废
	 * @param list
	 * @param codes
	 * @return
	 */
	public Long out(List list ,java.util.List<Code> codes)
	{
		
		list.setId(0);
		if (list.getNumber()==null||list.getWarehouse_id()<0||list.getType_id()<0) {
			return null;
		}
		if(list.getStocknumber()!=null)
		{
		
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("stocknumber", list.getStocknumber());
			map.put("type_id",list.getType_id());
			Ware ware = new Ware().get(map );
			if(ware!=null)
			{
				if(ware.getQuantity()-list.getQuantity()<0)
					return null;
				if(ware.getQuantity()-list.getQuantity()==0)
				{
					//删除
					ware.delete();
				}else {
					map.remove("stocknumber");
					map.remove("type_id");
					map.put("quantity", ware.getQuantity()-list.getQuantity());
					ware.update(map,ware.getId());
				}
			}else {
				return null;
				
			}
		}
		else {
			return null;
		}
		long id = list.save();
		if(id>0)
		{
			for (Code code : codes)
			{
				code.setList_id(id);
				code.save();
			}
		}
			return id;
		}
	
	
	/**
	 *  保存
	 * @param list
	 * @return
	 */
		public Long save(List list) 
		{
			list.setId(0);
			if (list.getNumber()==null||list.getWarehouse_id()<0||list.getType_id()<0) {
				return null;
			}
			
			long id = list.save();
			if(id>0)
			{
				
				//添加账单 只有在入库的时候才添加账单
				if(list.getSupply_id()!=null&&list.getPrice()*list.getQuantity()>0)
				{
					Bill bill = new Bill();
					bill.setList_id(id);
					bill.setSupply_id(list.getSupply_id());//供应商
					bill.setType_id(list.getType_id());
					bill.setPrice(list.getPrice());
					bill.setCost(list.getPrice()*list.getQuantity());
					bill.setQuantity(list.getQuantity());
					bill.save();
				}
				
				if(list.getStocknumber()!=null)
				{
					//添加库存
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("stocknumber", list.getStocknumber());
					map.put("type_id",list.getType_id());
					Ware ware = new Ware().get(map );
					if(ware==null)//没有库存就添加
					{
						Ware war = new Ware();
						war.setStocknumber(list.getStocknumber());
						war.setType_id(list.getType_id());
						war.setQuantity(list.getQuantity());
						war.save();
					}else {//有库存就修改
						map.remove("stocknumber");
						map.remove("type_id");
						map.put("quantity", list.getQuantity()+ware.getQuantity());
						ware.update(map,ware.getId());
						
					}
					
				}
			}
			return id;
	
		}
		
		
		
		
		/**
		 *  	添加清单
		 * @param list
		 * @param codes
		 * @return
		 */
		public Long save(List list ,java.util.List<Code> codes)
		{
			if (list.getNumber()==null||list.getWarehouse_id()<0||list.getType_id()<0) {
				return null;
			}
			
			long id = list.save();//保存
			/**
			 * 其实这里应该做事物处理
			 * todo
			 */
			if(id>0)
			{
				//添加一维码
				for (Code code : codes)
				{
					code.setList_id(id);
					code.save();
				}
				//添加账单 只有在入库的时候才添加账单
				if(list.getSupply_id()!=null&&list.getPrice()*list.getQuantity()>0)
				{
					Bill bill = new Bill();
					bill.setList_id(id);
					bill.setSupply_id(list.getSupply_id());//供应商
					bill.setType_id(list.getType_id());
					bill.setPrice(list.getPrice());
					bill.setCost(list.getPrice()*list.getQuantity());
					bill.setQuantity(list.getQuantity());
					bill.save();
				}
				
				if(list.getStocknumber()!=null)
				{
					//添加库存
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("stocknumber", list.getStocknumber());
					map.put("type_id",list.getType_id());
					Ware ware = new Ware().get(map );
					if(ware==null)//没有库存就添加
					{
						Ware war = new Ware();
						war.setStocknumber(list.getStocknumber());
						war.setType_id(list.getType_id());
						war.setQuantity(list.getQuantity());
						war.save();
					}else {//有库存就修改
						map.remove("stocknumber");
						map.remove("type_id");
						map.put("quantity", list.getQuantity()+ware.getQuantity());
						ware.update(map,ware.getId());
						
					}
					
				}
			}
		
		
			
			
//			PreparedStatement ps = null;
//			ResultSet rs = null;
//			String sql=null;
//			Connection con = null;
//			//实现事物处理
//			try {
//				con = getConnection();
//				con.setAutoCommit(false);// 更改JDBC事务的默认提交方式
//				QueryRunner runner = new QueryRunner();
//				 sql = "INSERT INTO `bems_list`(`number`, `status`, `quantity`, `price`, `type_id`, `user_id`, `admin_id`, `createtime`, `warehouse_id`,`supply_id`) VALUES (?,?,?,?,?,?,?,?,?,?)";
//				
//				ps=con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
//				ps.setObject(1, list.getNumber());
//				ps.setObject(2, list.getStatus());
//				ps.setObject(3, list.getQuantity());
//				ps.setObject(4, list.getPrice());
//				ps.setObject(5, list.getType_id());
//				ps.setObject(6, list.getUser_id());
//				ps.setObject(7, list.getAdmin_id());
//				ps.setObject(8, list.getCreatetime());
//				ps.setObject(9, list.getWarehouse_id());
//				ps.setObject(10, list.getSupply_id());
//				ps.executeUpdate();
//				rs = ps.getGeneratedKeys();
//				Long id = rs.next()?rs.getLong(1):-1;
//				if(id>0)
//				{
//					sql="INSERT INTO `bems_code`( `numbers`, `list_id`) VALUES (?,?)";
//					for (Code code : codes) 
//					{
//						runner.update(con, sql,code.getNumber(),id);
//					}
//				}
//				con.commit();//提交JDBC事务
//				con.setAutoCommit(true);// 恢复JDBC事务的默认提交方式
//				
//			} catch (SQLException e) {
//				try {
//					con.rollback();//回滚JDBC事务
//				} catch (SQLException e1) {}
//				
//			}
//			finally
//			{
//				DbUtils.closeQuietly(rs);
//				DbUtils.closeQuietly(ps);
//				sql = null;
//			}
//			return null;
			return id;
			
		}
		
		/**
		 * 
		 * @param page
		 * @param size
		 * @param start
		 * @param end
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public java.util.List<List> getLists(int page,int size,Timestamp start,Timestamp end)
		{
			
			String filter=" warehouse_id =1 and UNIX_TIMESTAMP(createtime) between  UNIX_TIMESTAMP('"+start+"') and UNIX_TIMESTAMP('"+end+"') ";
			return (java.util.List<List>) new List().filter(filter, page, size);
			
		}
		public java.util.List<List> getLists(int page,int size,int status)
		{
			
			String filter=" status="+status+" and warehouse_id =1  ";
			return (java.util.List<List>) new List().filter(filter, page, size);
			
			
		}
		public java.util.List<List> getListt(int page,int size,int type)
		{
			
			String filter=" status=1 and  type_id="+type+" and warehouse_id =1  ";
			return (java.util.List<List>) new List().filter(filter, page, size);
			
			
		}
		public java.util.List<List> getLists(int page,int size,Timestamp start,Timestamp end,int status)
		{
			
			String filter=" status="+status+" and warehouse_id =1 and UNIX_TIMESTAMP(createtime) between  UNIX_TIMESTAMP('"+start+"') and UNIX_TIMESTAMP('"+end+"') ";
			return (java.util.List<List>) new List().filter(filter, page, size);
			
		}
		public java.util.List<List> getLists(Timestamp start,Timestamp end)
		{
			
			String sql="SELECT * FROM `bems_list` where warehouse_id =1 and UNIX_TIMESTAMP(createtime) between  UNIX_TIMESTAMP(?) and UNIX_TIMESTAMP(?) ORDER BY id DESC";
			return QueryHelper.query(List.class, sql, start,end);
			
		}
		/**
		 * 
		 * @param page
		 * @param size
		 * @param start
		 * @param end  {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd hh:mm:ss"};
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public java.util.List<List> getLists(int page,int size,String start,String end)
		{
			
			String filter=" warehouse_id =1  UNIX_TIMESTAMP(createtime) between  UNIX_TIMESTAMP('"+start+"') and UNIX_TIMESTAMP('"+end+"') ";
			return (java.util.List<List>) new List().filter(filter, page, size);
			
		}
		
		public static void main(String[] args) throws ParseException {
			ListDao dao = new ListDao();
			List list = new List();
			String start="2012-11-12 00:00:00";
			String end="2012-12-14 00:00:00";
			String[] parsePatterns={"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd hh:mm:ss"};
			Date starttime = DateUtils.parseDate(start, parsePatterns);
			Date endtime = DateUtils.parseDate(end, parsePatterns);
			java.util.List<List> l = dao.getLists( new Timestamp(starttime.getTime()), new Timestamp(endtime.getTime()));
			System.out.println(l.size());
		
		}
}
